import { Body, Controller, Delete, Get, Param, Patch, Post, Query, Req } from '@nestjs/common'
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger'
import * as Config from 'config'
import { Permission } from '@/decorators/permission.decorator'
import { PagenationPipe } from '@/pipes/pagenation.pipe'
import { QueryEmptyTrimPipe } from '@/pipes/queryEmptyTrim.pipe'
import { CreateUserDto } from './dto/create-user.dto'
import { GetUserDto } from './dto/get-user.dto'
import { UpdateUserDto } from './dto/update-user.dto'
import { UsersService } from './users.service'
@ApiBearerAuth()
@ApiTags('用户模块')
@Controller('systemManage')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Post('createUser')
  @ApiOperation({ summary: '创建用户' })
  @ApiBody({ type: CreateUserDto })
  create(@Body() createUserDto: CreateUserDto) {
    return this.usersService.create(createUserDto)
  }

  @Get('getUserList')
  @ApiOperation({ summary: '获取用户列表' })
  async findAll(@Query(PagenationPipe, QueryEmptyTrimPipe) query: GetUserDto) {
    const result = await this.usersService.findAll(query)
    return {
      ...result,
      records: result.records
        .filter(
          (userItem) =>
            !userItem.roles.length ||
            userItem.roles.some(
              (roleItem) => roleItem.role.roleCode !== Config.get('role').superAdminCode
            )
        )
        .map((item) => {
          const { roles, ...rest } = item
          const userRoles = roles.map((userRole) => userRole.role.roleCode)
          return {
            ...rest,
            userRoles,
          }
        }),
    }
  }

  @Patch('updateUser/:id')
  @ApiOperation({ summary: '编辑用户' })
  @ApiBody({ type: UpdateUserDto })
  @Permission('system:user:edit')
  update(
    @Req() req: { user: PayloadUserType },
    @Param('id') id: string,
    @Body() updateUserDto: UpdateUserDto
  ) {
    return this.usersService.update(id, updateUserDto, req.user)
  }

  @Delete('deleteUser/:ids')
  @ApiOperation({ summary: '删除用户' })
  @ApiParam({ name: 'ids', description: '用户ids' })
  remove(@Param('ids') ids: string) {
    const deleteIds = ids.split(',').map((id) => +id)
    return this.usersService.remove(deleteIds)
  }
}
